package com.gyg.util;

import com.gyg.common.VO.UploadFileVO;
import com.gyg.common.lang.Result;
import com.gyg.service.IFileService;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPSServerSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <des>
 *
 * <des>
 *
 * @create Date 2021-11-02
 **/
public class FTPUtil {

    //用于打印日志
    private static final Logger log = LoggerFactory.getLogger(FTPUtil.class);

    //设置私有不能实例化
    private FTPUtil() {

    }

    /**
     * 上传
     *
     * @param hostname ip或域名地址
     * @param port  端口
     * @param username 用户名
     * @param password 密码
     * @param workingPath 服务器的工作目
     * @param inputStream 要上传文件的输入流
     * @param saveName    设置上传之后的文件名
     * @return
     */
    public static void upload(String hostname, int port, String username, String password, String workingPath, InputStream inputStream, String saveName) {
        FTPClient ftpClient = new FTPClient();
        //1 测试连接
        try {
            //ftp初始化的一些参数
            ftpClient.connect(hostname, port);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.setControlEncoding("UTF-8");
            //1 测试连接
            if (ftpClient.login(username, password)) {
                log.info("连接ftp成功");
                //2 检查工作目录是否存在
                if(ftpClient.changeWorkingDirectory(workingPath)) {
                    // 3 检查是否上传成功
                    if (ftpClient.storeFile(saveName, inputStream)) {
                        log.error("上传成功");
                        ftpClient.disconnect();
                        log.error("已关闭连接");
                    }
                }
            } else {
                log.error("连接ftp失败，可能用户名或密码错误");
                try {
                    ftpClient.disconnect();
                    log.error("已关闭连接");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            log.error("连接失败，可能ip或端口错误");
            e.printStackTrace();
        }

    }

    public static List<UploadFileVO> getUploadFileList(){
        FTPClient ftpClient = new FTPClient();
        List<UploadFileVO> list = new ArrayList<>();
        //1 测试连接
        try {
            //ftp初始化的一些参数
            ftpClient.connect("192.168.123.96",12333);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.setControlEncoding("UTF-8");
            //1 测试连接
            if (ftpClient.login("pc","123456")) {
                log.info("连接ftp成功");
                //2 检查工作目录是否存在
                if (ftpClient.changeWorkingDirectory("/upload")) {
                         for (FTPFile ftpFile:ftpClient.listFiles()){
                             UploadFileVO uploadFileVO = new UploadFileVO();
                             uploadFileVO.setFileName(ftpFile.getName());
                             uploadFileVO.setCreated(ftpFile.getTimestamp().getTime());
                             uploadFileVO.setUrl("ftp://192.168.123.96:12333/upload/"+ftpFile.getName());
                             list.add(uploadFileVO);
                         }
                    log.info("获取文件列表完毕");
                    ftpClient.disconnect();
                    log.error("已关闭连接");
                }
            }else {
                log.error("连接ftp失败，可能用户名或密码错误");
                try {
                    ftpClient.disconnect();
                    log.error("已关闭连接");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            log.error("连接失败，可能ip或端口错误");
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 断开连接
     *
     * @param ftpClient
     * @throws Exception
     */
    public static void disconnect(FTPClient ftpClient) {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
                log.error("已关闭连接");
            } catch (IOException e) {
                log.error("没有关闭连接");
                e.printStackTrace();
            }
        }
    }

    /**
     * 测试是否能连接
     *
     * @param ftpClient
     * @param hostname  ip或域名地址
     * @param port      端口
     * @param username  用户名
     * @param password  密码
     * @return 返回真则能连接
     */
    public static boolean connect(FTPClient ftpClient, String hostname, int port, String username, String password) {
        boolean flag = false;
        try {
            //ftp初始化的一些参数
            ftpClient.connect(hostname, port);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.setControlEncoding("UTF-8");
            if (ftpClient.login(username, password)) {
                log.info("连接ftp成功");
                flag = true;
            } else {
                log.error("连接ftp失败，可能用户名或密码错误");
                try {
                    disconnect(ftpClient);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            log.error("连接失败，可能ip或端口错误");
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 上传文件
     *
     * @param ftpClient
     * @param saveName        全路径。如/home/public/a.txt
     * @param fileInputStream 要上传的文件流
     * @return
     */
    public static boolean storeFile(FTPClient ftpClient, String saveName, InputStream fileInputStream) {
        boolean flag = false;
        try {
            if (ftpClient.storeFile(saveName, fileInputStream)) {
                flag = true;
                log.error("上传成功");
                disconnect(ftpClient);
            }
        } catch (IOException e) {
            log.error("上传失败");
            disconnect(ftpClient);
            e.printStackTrace();
        }
        return flag;
    }
}
